package com.ctshk.rpc.order.scenic.service.impl.app;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.AppReq;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.order.scenic.dto.MyScenicOrderDTO;
import com.ctshk.rpc.order.scenic.dto.app.ScenicOrderAppOrderDetailDTO;
import com.ctshk.rpc.order.scenic.dto.app.ScenicOrderAppOrderDetailTouristDTO;
import com.ctshk.rpc.order.scenic.dto.app.ScenicOrderPayDTO;
import com.ctshk.rpc.order.scenic.entity.app.ScenicOrder;
import com.ctshk.rpc.order.scenic.entity.app.ScenicOrderCollection;
import com.ctshk.rpc.order.scenic.entity.app.ScenicOrderTourist;
import com.ctshk.rpc.order.scenic.mapper.app.ScenicOrderAppMapper;
import com.ctshk.rpc.order.scenic.mapper.app.ScenicOrderCollectionAppMapper;
import com.ctshk.rpc.order.scenic.mapper.app.ScenicOrderTouristAppMapper;
import com.ctshk.rpc.order.scenic.req.app.*;
import com.ctshk.rpc.order.scenic.service.app.IScenicOrderAppService;
import com.ctshk.rpc.order.scenic.service.app.IScenicOrderReceiptAppService;
import com.ctshk.rpc.order.scenic.service.app.ScenicOrderUtilService;
import com.ctshk.rpc.payment.enums.PayCurrency;
import com.ctshk.rpc.payment.enums.PaymentMethod;
import com.ctshk.rpc.payment.req.PayCommonReq;
import com.ctshk.rpc.payment.service.IPayService;
import com.ctshk.rpc.scenic.dto.ScenicProductCostStrategySpecStockDTO;
import com.ctshk.rpc.scenic.dto.ScenicProductListDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDetailDTO;
import com.ctshk.rpc.scenic.dto.app.inner.ScenicProductAttrListDTO;
import com.ctshk.rpc.scenic.service.IScenicProductService;
import com.ctshk.rpc.scenic.service.ScenicProductCostStrategySpecStockService;
import com.ctshk.rpc.scenic.service.app.IScenicProductAppService;
import com.ctshk.rpc.scenic.service.app.IScenicProductCostStrategySpecAttrAppService;
import com.ctshk.rpc.scenic.service.app.IScenicTicketEsSearchService;
import com.ctshk.rpc.system.dto.ScenicDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.DispatchOrderRuleGetUserReq;
import com.ctshk.rpc.system.service.IDispatchOrderRuleService;
import com.ctshk.rpc.system.service.ISceneService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.user.service.IOrderEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.ctshk.common.utils.CharUtil.charsAll;

@Slf4j
@DubboService
public class ScenicOrderAppServiceImpl implements IScenicOrderAppService {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    ScenicOrderAppMapper scenicOrderAppMapper;
    @Autowired
    ScenicOrderTouristAppMapper scenicOrderTouristAppMapper;
    @Autowired
    ScenicOrderCollectionAppMapper scenicOrderCollectionAppMapper;
    @DubboReference
    ISceneService iSceneService;

    @DubboReference
    IScenicTicketEsSearchService iScenicTicketEsSearchService;
    @DubboReference
    IPayService iPayService;
    @DubboReference
    IDispatchOrderRuleService dispatchOrderRuleService;
    @DubboReference
    ISysUserService sysUserService;
    @DubboReference
    IScenicOrderReceiptAppService iScenicOrderReceiptAppService;
    @DubboReference
    IScenicProductAppService iScenicProductAppService;
    @DubboReference
    IScenicProductCostStrategySpecAttrAppService iScenicProductCostStrategySpecAttrAppService;
    @DubboReference
    private IScenicProductService scenicProductService;
    @DubboReference
    private IOrderEsService orderEsService;
    @DubboReference
    ScenicProductCostStrategySpecStockService scenicProductCostStrategySpecStockService;

    /**
     * 提交订单
     * @param req
     * @param appReq
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Long> addOrderInfo(ScenicOrderAppPlaceOrderReq req, AppReq appReq) {
        if (req.getTouristList() == null || req.getTouristList().size() < 1) {
            return Result.failed(SystemError.SCENIC_5019, "最少有一个旅客！");
        }
        ScenicOrder scenicOrder = EntityUtil.copy(req,ScenicOrder.class);
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        // 获取销售人
        UserDTO userDTO = getSaleMan(scenicOrder, appReq.getCompanyType(), nowLocalDateTime);
        if (userDTO != null) {
            scenicOrder.setSalesmanId(userDTO.getId());
            scenicOrder.setSalesmanName(userDTO.getFullName());
        }
        {// 设置随机的查询编号
            String queryNumber = generateQueryNumber(4, 6);
            if (queryNumber != null) {
                scenicOrder.setQueryNumber(queryNumber);
            }
        }

        scenicOrder.setSalesMethods(1);
        // 设置待付款时间 + 30分钟
        scenicOrder.setPayExpireDate(nowLocalDateTime.plusMinutes(30));
        scenicOrder.setPaymentStatus(OrderPaymentStatus.UN_PAYMENT.getCode());
        scenicOrder.setGmtModified(nowLocalDateTime);
        //生成景点门票销售编号=J+部门代码+员工编号+年后2位+月日4位+3位随机数字
        String orderNumber = generatorOrderNumber(userDTO, nowLocalDateTime);
        scenicOrder.setOrderNumber(orderNumber);

        scenicOrder.setOrderAmount(req.getOrderAmount());
        scenicOrder.setReceivableAmount(req.getOrderAmount());

        scenicOrder.setSurname(req.getContactEnSurname());
        scenicOrder.setName(req.getContactEnName());
        scenicOrder.setContactName(req.getContactEnSurname()+""+req.getContactEnName());
        scenicOrder.setTicketsFee(req.getOrderAmount());
        scenicOrder.setServiceFee(req.getReserveCharge().multiply(BigDecimal.valueOf(req.getProductTicketNumber())));
        scenicOrder.setSource(appReq.getOrderSource());

        // 设置C端下单用户id
        scenicOrder.setUserId(req.getUserId());
        scenicOrder.setStockId(req.getStockId());
        scenicOrderAppMapper.insert(scenicOrder);

        List<ScenicOrderAppPlaceOrderTouristReq> touristList = req.getTouristList();
        if (touristList != null && touristList.size() > 0) {
            for (ScenicOrderAppPlaceOrderTouristReq scenicOrderAppPlaceOrderTouristReq : touristList) {
                ScenicOrderTourist scenicOrderTourist = new ScenicOrderTourist();
                BeanUtils.copyProperties(scenicOrderAppPlaceOrderTouristReq, scenicOrderTourist);
                // 设置证件信息
                List<PassengerCertificatesListDTO> passengerCertificatesList = scenicOrderAppPlaceOrderTouristReq.getPassengerCertificatesList();
                if (passengerCertificatesList != null && passengerCertificatesList.size() > 0) {
                    PassengerCertificatesListDTO passengerCertificatesListDTO = passengerCertificatesList.get(0);
                    scenicOrderTourist.setCertificatesNumber(passengerCertificatesListDTO.getCertificatesNumber());
                    scenicOrderTourist.setCertificatesType(passengerCertificatesListDTO.getCertificatesTypeName());
                    scenicOrderTourist.setCertificatesTypeId(passengerCertificatesListDTO.getCertificatesTypeId());
                }
                scenicOrderTourist.setContactMobile(scenicOrderAppPlaceOrderTouristReq.getMobile());
                scenicOrderTourist.setContactMobileAreaCode(scenicOrderAppPlaceOrderTouristReq.getMobileAreaCode());
                scenicOrderTourist.setGmtModified(nowLocalDateTime);
                scenicOrderTourist.setOrderId(scenicOrder.getId());
                int insert = scenicOrderTouristAppMapper.insert(scenicOrderTourist);
            }
        }
        // 生成收据信息
        insertScenicOrderReceipt(scenicOrder, userDTO, nowLocalDateTime);
        sendOrderToAppUser(scenicOrder.getId());
        return Result.success(scenicOrder.getId());
    }

    // 生成收据信息
    private void insertScenicOrderReceipt(ScenicOrder scenicOrder, UserDTO userDTO, LocalDateTime nowLocalDateTime) {
        String receiptNumber = generatorReceiptNumber(userDTO, nowLocalDateTime);
        ScenicOrderReceiptReq scenicOrderReceiptReq = new ScenicOrderReceiptReq();
        scenicOrderReceiptReq.setId(SnowflakeIdWorker.nextId());
        scenicOrderReceiptReq.setOrderId(scenicOrder.getId());
        scenicOrderReceiptReq.setReceiptNo(receiptNumber);
        if (userDTO != null) {
            scenicOrderReceiptReq.setBranch(userDTO.getDept());
            scenicOrderReceiptReq.setCreateId(userDTO.getId());
            scenicOrderReceiptReq.setModifiedId(userDTO.getId());
        }
        scenicOrderReceiptReq.setGuest(scenicOrder.getContactName());
        scenicOrderReceiptReq.setPhone(scenicOrder.getContactMobileAreaCode() + "-" + scenicOrder.getContactMobile());
        scenicOrderReceiptReq.setIsDeleted(IsDeletedCode.NO.getCode());
        scenicOrderReceiptReq.setGmtCreate(nowLocalDateTime);
        scenicOrderReceiptReq.setGmtModified(nowLocalDateTime);
        iScenicOrderReceiptAppService.insertScenicOrderReceipt(scenicOrderReceiptReq);
    }

    /**
     * 查询订单详情
     * @param orderId
     * @return
     */
    @Override
    public Result<ScenicOrderAppOrderDetailDTO> selectOrderInfo(Long orderId) {
        ScenicOrderAppOrderDetailDTO scenicOrderAppOrderDetailDTO = new ScenicOrderAppOrderDetailDTO();
        String s = redisTemplate.opsForValue().get(RedisConstants.SCENIC_ORDER_DETAIL + orderId);
        if (s == null) {
            ScenicOrder scenicOrder = scenicOrderAppMapper.selectById(orderId);
            if (scenicOrder != null) {
                BeanUtils.copyProperties(scenicOrder, scenicOrderAppOrderDetailDTO);
                // 查询联系人信息
                Map<String, Object> map = new HashMap<>();
                map.put("order_id", scenicOrder.getId());
                List<ScenicOrderTourist> scenicOrderTourists = scenicOrderTouristAppMapper.selectByMap(map);
                if (scenicOrderTourists != null && scenicOrderTourists.size() > 0) {
                    List<ScenicOrderAppOrderDetailTouristDTO> touristList = scenicOrderAppOrderDetailDTO.getTouristList();
                    for (ScenicOrderTourist scenicOrderTourist : scenicOrderTourists) {
                        try {
                            ScenicOrderAppOrderDetailTouristDTO scenicOrderAppOrderDetailTouristDTO = new ScenicOrderAppOrderDetailTouristDTO();
                            BeanUtils.copyProperties(scenicOrderTourist, scenicOrderAppOrderDetailTouristDTO);
                            touristList.add(scenicOrderAppOrderDetailTouristDTO);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                    }
                    scenicOrderAppOrderDetailDTO.setTouristList(touristList);
                }
                {
                    ScenicProductDTO scenicProductDTO = iScenicProductAppService.selectScenicProductDTOById(scenicOrderAppOrderDetailDTO.getProductId());
                    if (scenicProductDTO != null) {
                        // 设置预定服务费类型
                        scenicOrderAppOrderDetailDTO.setReserveChargeType(scenicProductDTO.getReserveChargeType());
                        // 设置预定服务费
                        scenicOrderAppOrderDetailDTO.setReserveCharge(scenicOrder.getServiceFee());
                        scenicOrderAppOrderDetailDTO.setProductName(scenicProductDTO.getName());
                        scenicOrderAppOrderDetailDTO.setCustomerNotice(scenicProductDTO.getCustomerNotice());

                        //设置产品信息
                        ScenicDTO scenicDto = iSceneService.quertByiId(scenicProductDTO.getScenicId());
                        if (null != scenicDto){
                            scenicOrderAppOrderDetailDTO.setScenicLocation(scenicDto.getScenicLocation());
                            scenicOrderAppOrderDetailDTO.setCoverPhoto(scenicDto.getCoverPhoto());
                        }
                    }
                    if (scenicOrderAppOrderDetailDTO.getProductTicketsId() != null && !scenicOrderAppOrderDetailDTO.getProductTicketsId().equals("")) {
                        /*ScenicProductCostStrategySpecAttrAppDTO scenicProductCostStrategySpecAttrAppDTO = iScenicProductCostStrategySpecAttrAppService.selectById(Long.valueOf(scenicOrderAppOrderDetailDTO.getProductTicketsId()));
                        if (scenicProductCostStrategySpecAttrAppDTO != null) {
                            scenicOrderAppOrderDetailDTO.setAttrTypeName(scenicProductCostStrategySpecAttrAppDTO.getSpecName());
                            scenicOrderAppOrderDetailDTO.setAttrName(scenicProductCostStrategySpecAttrAppDTO.getAttributeName());
                        }*/
                        ScenicProductCostStrategySpecStockDTO pecStockObj = scenicProductCostStrategySpecStockService.selectById(scenicOrder.getStockId());
                        if (!Objects.isNull(pecStockObj)){
                            scenicOrderAppOrderDetailDTO.setAttr1Name(pecStockObj.getAttr1Name());
                            scenicOrderAppOrderDetailDTO.setAttr2Name(pecStockObj.getAttr2Name());
                        }

                    }
                }
                // 30 - 90 分钟失效
                int time = 30 + new Random().nextInt(60);
                redisTemplate.opsForValue().set(RedisConstants.SCENIC_ORDER_DETAIL + orderId, JSON.toJSONString(scenicOrderAppOrderDetailDTO), time, TimeUnit.MINUTES);
                scenicOrderAppOrderDetailDTO.setOrderId(orderId);
            }
        } else {
            scenicOrderAppOrderDetailDTO = JSON.parseObject(s, ScenicOrderAppOrderDetailDTO.class);
        }
        return Result.success(scenicOrderAppOrderDetailDTO);
    }

    /**
     * 查询订单付款信息
     * @param orderId
     * @return
     */
    @Override
    public Result<ScenicOrderPayDTO> selectOrderPayInfo(Long orderId) {
        ScenicOrderPayDTO scenicOrderPayDTO = new ScenicOrderPayDTO();
        Result<ScenicOrderAppOrderDetailDTO> scenicOrderAppOrderDetailDTOResult = selectOrderInfo(orderId);
        if (scenicOrderAppOrderDetailDTOResult.isSuccess()) {
            ScenicOrderAppOrderDetailDTO scenicOrderAppOrderDetailDTO = scenicOrderAppOrderDetailDTOResult.getData();
            if (scenicOrderAppOrderDetailDTO != null && !Objects.isNull(scenicOrderAppOrderDetailDTO)) {
                //订单号、产品名称、总金额
                scenicOrderPayDTO.setScheduleNumber(scenicOrderAppOrderDetailDTO.getOrderNumber());
                scenicOrderPayDTO.setProductName(scenicOrderAppOrderDetailDTO.getProductName());
                scenicOrderPayDTO.setTotalPrice(scenicOrderAppOrderDetailDTO.getOrderAmount());
                scenicOrderPayDTO.setPayExpireDate(scenicOrderAppOrderDetailDTO.getPayExpireDate());
                scenicOrderPayDTO.setGmtCreate(scenicOrderAppOrderDetailDTO.getGmtCreate());
                ScenicProductEsDetailDTO scenicProductEsDetailDTO = iScenicTicketEsSearchService.selectScenicDetailEs(null, scenicOrderAppOrderDetailDTO.getProductId(), null);
                if (scenicProductEsDetailDTO != null) {
                    // 服务费
                    scenicOrderPayDTO.setReserveCharge(scenicProductEsDetailDTO.getReserveCharge());
                    // 规格名称
                    List<ScenicProductAttrListDTO> ticketList = scenicProductEsDetailDTO.getTicketList();
                    if (ticketList.size() > 0) {
                        String productTicketsId = scenicOrderAppOrderDetailDTO.getProductTicketsId();
                        if (productTicketsId != null) {
                            String[] split = productTicketsId.split(",");
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String s : split) {
                                for (ScenicProductAttrListDTO scenicProductAttrListDTO : ticketList) {
                                    //if (s.equals(scenicProductAttrListDTO.getId())) {
                                    stringBuilder.append(scenicProductAttrListDTO.getTitle()).append(",");
                                    //}
                                }
                            }
                            //产品规格名称
                            scenicOrderPayDTO.setSpecialName(stringBuilder.toString());
                            // 判断类型，获取有效期，
                            //if (scenicProductEsDetailDTO.getValidType() != null){
                            if (scenicProductEsDetailDTO.getValidDay() != null){
                                scenicOrderPayDTO.setValidDay(String.valueOf(scenicProductEsDetailDTO.getValidDay()));
                            }else if (scenicProductEsDetailDTO.getValidType() != null && scenicProductEsDetailDTO.getValidDayEnd() != null){
                                scenicOrderPayDTO.setValidDay(scenicProductEsDetailDTO.getValidDayBegin()+"至"+scenicProductEsDetailDTO.getValidDayEnd());
                            }
                        }
                    }
                }
            }
        }
        return Result.success(scenicOrderPayDTO);
    }

    @Override
    public Result callPay(ScenicOrderCallPayReq req) {
        log.info("【景点门票订单APP-唤起支付】方法入参:{}", JSON.toJSONString(req));
        Result pay = null;
        try {
            ScenicOrder scenicOrder = scenicOrderAppMapper.selectOne(new QueryWrapper<ScenicOrder>().lambda()
                    .eq(ScenicOrder::getId, req.getId()));
            if (null == scenicOrder) {
                throw new BusinessException(SystemError.SCENIC_5016);
            }
            PayCommonReq payCommonReq = new PayCommonReq();
//            payCommonReq.setOrderNumber(scenicOrder.getOrderNumber());
            payCommonReq.setOrderValidTime(scenicOrder.getPayExpireDate());
            payCommonReq.setCurrency(PayCurrency.HKD);
            payCommonReq.setTotalFee(scenicOrder.getReceivableAmount());
            payCommonReq.setPaymentMethod(PaymentMethod.getByPayRefundMethodId(req.getPayRefundMethodId()));
            payCommonReq.setNotifyUrl("/app/order/scenic/app/payment");
            payCommonReq.setSubject("支付");
            payCommonReq.setBody("支付");
            log.info("【景点门票APP-唤起支付】支付入参:{},userId:{}", JSON.toJSONString(payCommonReq), scenicOrder.getSalesmanId());
            pay = iPayService.pay(payCommonReq, scenicOrder.getSalesmanId());
            log.info("【景点门票订单APP-唤起支付】支付回参:{}", JSON.toJSONString(pay));
        } catch (BusinessException e) {
            log.error("【景点门票订单APP-唤起支付】唤起支付失败失败,error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.getDefined(e.getCode()));
        } catch (Exception e) {
            log.error("【景点门票订单APP-唤起支付】系统异常,error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.SYS_500);
        }
        return pay;
    }

    @Override
    public Result payment(ScenicOrderConsumeReq scenicOrderConsumeReq) {
        log.info("【景点门票订单APP-支付订单】方法入参:{}", JSON.toJSONString(scenicOrderConsumeReq));
        try {
            ScenicOrder scenicOrder = scenicOrderAppMapper.selectOne(new QueryWrapper<ScenicOrder>().lambda()
                    .eq(ScenicOrder::getOrderNumber, scenicOrderConsumeReq.getOrderNumber())
                    .eq(ScenicOrder::getIsDeleted, IsDeletedCode.NO.getCode()));
            if (scenicOrder == null) {
                throw new BusinessException(SystemError.SCENIC_5016);
            }
            LocalDateTime nowLocalDateTime = LocalDateTime.now();
            if (nowLocalDateTime.isAfter(scenicOrder.getPayExpireDate())) {
                // 支付超时
                throw new BusinessException(SystemError.SCENIC_5017);
            }
            scenicOrder.setPaymentStatus(OrderPaymentStatus.ALREADY_PAYMENT.getCode());
            // 计算支付总金额和支付记录
            BigDecimal readyMoney = scenicOrderConsumeReq.getAmount();//实收金额(港币)
            BigDecimal amountCountHKD = BigDecimal.ZERO;//订单金额(港币)=实收金额+积分抵扣+优惠券
            PaymentMethod paymentMethod = PaymentMethod.getByCode(scenicOrderConsumeReq.getPaymentMethod());
            String paymentNumber = ScenicOrderUtilService.generatorPaymentNumber(nowLocalDateTime);
            ScenicOrderCollection scenicOrderCollection = new ScenicOrderCollection();
            scenicOrderCollection.setGmtCreate(nowLocalDateTime);
            scenicOrderCollection.setOrderId(scenicOrder.getId());
            scenicOrderCollection.setCollectionAmount(readyMoney);
            scenicOrderCollection.setGmtModified(nowLocalDateTime);
            scenicOrderCollection.setId(SnowflakeIdWorker.nextId());
            scenicOrderCollection.setCollectionNumber(paymentNumber);
            scenicOrderCollection.setCurrencyId(Currency.HKD.getCode());
            scenicOrderCollection.setCurrency(Currency.HKD.getCurrency());
            scenicOrderCollection.setIsDeleted(IsDeletedCode.NO.getCode());
            scenicOrderCollection.setCollectionWay(paymentMethod.getName());   //付款方式
            scenicOrderCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
            scenicOrderCollection.setPayer(scenicOrderConsumeReq.getPaymentAccount()); //付款账号
            scenicOrderCollection.setCollectionWayId(paymentMethod.getPayRefundMethodId()); //付款方式
            scenicOrderCollectionAppMapper.insert(scenicOrderCollection);
            updateStatusToAppUser(scenicOrder.getId());
        } catch (BusinessException e) {
            log.error("【景点门票-唤起支付】唤起支付失败失败,error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.getDefined(e.getCode()));
        } catch (Exception e) {
            log.error("【景点门票订单APP-唤起支付】系统异常,error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.SUPPLIER_BOOKING_13702);
        }
        return Result.success();
    }

    // 获取销售人信息
    private UserDTO getSaleMan(ScenicOrder scenicOrder, String companyType, LocalDateTime now) {
        DispatchOrderRuleGetUserReq dispatchOrderRuleGetUserReq = new DispatchOrderRuleGetUserReq();
        dispatchOrderRuleGetUserReq.setBusinessTypeId(SystemBusinessType.ATTRACTION_TICKET.getCode());
        dispatchOrderRuleGetUserReq.setCompanyType(companyType);
        Result<Long> result = null;
        try {
            result = dispatchOrderRuleService.getDispatchUserId(dispatchOrderRuleGetUserReq);
        } catch (Exception e) {
//            log.error("【景点门票APP-提交订单】获取销售人失败:{},msg:{}", result.getCode(), result.getMsg());
        }

//        if (!result.isSuccess()) {
//            throw new BusinessException(SystemError.getDefined(result.getCode()));
//        }
        UserDTO saleUser = null;
        try {
            if (result != null) {
                saleUser = sysUserService.queryCacheUser(result.getData());
                String orderNumber = generatorOrderNumber(saleUser, now);
                scenicOrder.setOrderNumber(orderNumber);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("景点门票-查询销售用户信息服务失败");
        }
        return saleUser;
    }

    @Override
    public Result<Boolean> cancelOrder(Long orderId) {
        Result<ScenicOrderAppOrderDetailDTO> scenicOrderAppOrderDetailDTOResult = selectOrderInfo(orderId);
        if (scenicOrderAppOrderDetailDTOResult.isSuccess()) {
            ScenicOrderAppOrderDetailDTO scenicOrderAppOrderDetailDTO = scenicOrderAppOrderDetailDTOResult.getData();
            if (scenicOrderAppOrderDetailDTO != null) {
                ScenicOrder scenicOrder = new ScenicOrder();
                BeanUtils.copyProperties(scenicOrderAppOrderDetailDTO, scenicOrder);
                try {
                    BeanUtils.copyProperties(scenicOrderAppOrderDetailDTO, scenicOrder);
                    scenicOrderAppMapper.updateById(scenicOrder);
                    updateStatusToAppUser(scenicOrder.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.success(true);
    }

    /**
     * 生成景点门票销售编号=J+部门代码+员工编号+年后2位+月日4位+3位随机数字
     *
     * @param userDTO
     * @return
     */
    public static String generatorOrderNumber(UserDTO userDTO, LocalDateTime nowLocalDateTime) {
        String employeeNumber = "";
        String deptCode = "";
        if (userDTO != null) {
            employeeNumber = userDTO.getEmployeeNumber();
            deptCode = userDTO.getDeptCode();
        }
        String date = DateUtil.fmt(nowLocalDateTime, "yyMMdd");
        String randomNumber = String.valueOf((int) ((Math.random() * 9 + 1) * 100));
        StringBuilder orderNumberSb = new StringBuilder();
        orderNumberSb.append("J").append(deptCode).append(employeeNumber).append(date).append(randomNumber);
        return orderNumberSb.toString().toUpperCase();
    }

    public static String generateQueryNumber(int i, int j) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int a = 0; a < i; a++) {
            int number = random.nextInt(52);
            sb.append(charsAll.charAt(number));
        }
        for (int b = 0; b < j; b++) {
            sb.append((int) (Math.random() * 10));
        }
        return sb.toString();
    }

    public static String generatorReceiptNumber(UserDTO userDTO, LocalDateTime nowLocalDateTime) {
        String symbol = "-";
        if (userDTO != null) {
            String employeeNumber = userDTO.getEmployeeNumber();
            String deptCode = userDTO.getDeptCode();
            String date = DateUtil.fmt(nowLocalDateTime, "yyMMdd");
            String time = DateUtil.fmt(nowLocalDateTime, "HHmmss");
            StringBuilder receiptNumberSb = new StringBuilder();
            receiptNumberSb.append("XS").append(symbol).append(deptCode).append(symbol)
                    .append(employeeNumber).append(symbol)
                    .append(date).append("-B-")
                    .append(time).append("（S）");
            return receiptNumberSb.toString().toUpperCase();
        }
        return "";
    }

    /**
     * 构建订单ESDTO
     * @param orderId
     * @return
     */
    public MyScenicOrderDTO buildEsOrderDTO(Long orderId) {
        ScenicOrder order = scenicOrderAppMapper.selectById(orderId);
        MyScenicOrderDTO orderDTO = EntityUtil.copy(order, MyScenicOrderDTO.class);

        Result<ScenicProductListDTO> scenicProductListDTOResult = scenicProductService.queryById(orderDTO.getProductId());
        if (scenicProductListDTOResult.isSuccess()) {
            ScenicProductListDTO data = scenicProductListDTOResult.getData();
            if(data.getVaildType() == 1) {
                Double vaildDay = data.getVaildDay();
                LocalDateTime gmtCreate = orderDTO.getGmtCreate();
                orderDTO.setVaildDayBegin(gmtCreate);
                orderDTO.setVaildDayEnd(gmtCreate.plusDays(vaildDay.longValue()));
                orderDTO.setProductName(data.getName());
            } else if(data.getVaildType() == 2){
                orderDTO.setVaildDayBegin(data.getVaildDayBegin());
                orderDTO.setVaildDayEnd(data.getVaildDayEnd());
                orderDTO.setProductName(data.getName());
            }
        }

        return orderDTO;
    }

    /**
     * 异步发送订单数据到个人中心
     * @param orderId 订单Id
     */
    public void sendOrderToAppUser(Long orderId) {
        CompletableFuture.runAsync(() -> {
            try {
                MyScenicOrderDTO orderDTO = buildEsOrderDTO(orderId);
                orderEsService.saveOrderToEs(orderDTO, SystemBusinessType.ATTRACTION_TICKET);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 异步更新订单状态到个人中心
     */
    public void updateStatusToAppUser(Long orderId) {
        CompletableFuture.runAsync(() -> {
            try {
                ScenicOrder order = scenicOrderAppMapper.selectById(orderId);
                orderEsService.updateStatusToEs(order.getId(),SystemBusinessType.ATTRACTION_TICKET.getCode(),
                        null, order.getPaymentStatus(), order.getScheduledStatus(),
                        order.getCancelStatus());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

